package com.finger.forest.base;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.finger.forest.R;
import com.finger.forest.dialog.CustomProgressDialog;
import com.finger.forest.http.Constant;
import com.finger.forest.service.LocationService;
import com.finger.forest.utils.StringUtil;
import com.finger.forest.utils.encode.PrefsUtil;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * activity基类
 */
public abstract class BaseActivity<T extends BasePresenter> extends AppCompatActivity {
    protected Context context;
    protected Activity activity;

    private CustomProgressDialog pd;

    protected TextView nav_title;


    protected T presenter;
    protected Gson gson;

    private Unbinder unbinder;

    protected int drUid;
    protected String token;

    protected int pageNUm = 1;
    protected int pageSize = 10;
    protected boolean isRefresh;

    //权限相关
    private final String TAG = BaseActivity.class.getSimpleName();
    private int REQUEST_CODE_PERMISSION = 0;
    protected Map<String, Object> netMap;

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(setView());
        unbinder = ButterKnife.bind(this);
        context = this;
        activity = this;
        drUid = PrefsUtil.getInt(context, CommonKey.USER_ID);
        token = PrefsUtil.getString(context, CommonKey.TOKEN);

        //保持竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        initMapView(savedInstanceState);
        gson = new Gson();
//        gpsPresenter = new GPSPresenter(this, this);

//        dataManager = DataManager.getInstance(this);
        initPresenter();
        initializeAdvance();
    }

    protected void initPresenter() {
        //mvp about
        presenter = TUtil.getT(this, 0);
        if (presenter != null) {
            if (this instanceof BaseView) {
                presenter.attachView(this, context);
            }
        }
    }


    /**
     * 初始化地图
     *
     * @param savedInstanceState 地图初始化需要savedInstanceState
     */
    protected void initMapView(Bundle savedInstanceState) {

    }

    protected int currentPageIndex = 1; // 当前页码1

    protected enum STATE {REFRESH, LOADMORE}

    protected STATE scrollState = STATE.REFRESH;
    protected SmartRefreshLayout smartRefreshLayout;

    /**
     * 刷新或者加载更多逻辑操作
     *
     * @param currentPageIndex 页码
     * @param state            刷新，加载更多
     */
    protected void refreshOrLoadmore(int currentPageIndex, STATE state) {
    }

    /**
     * 设置activity显示的R.layout视图
     */
    protected abstract int setView();

    protected void initializeAdvance() {
        receiveData();
        initializeView();
        loadDataFromServer();
    }

    protected void setTvTitle(String title) {
        if (nav_title != null) {
            nav_title.setText(title);
        }
    }

    /**
     * 接受数据
     */
    protected abstract void receiveData();

    protected void setRefreshView() {
    }

    // 打电话
    protected void callPhone(String phone) {
        if (StringUtil.isBlank(phone)) {
            Toast.makeText(context, "手机号码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_CALL);
        //url:统一资源定位符
        //uri:统一资源标示符（更广）
        intent.setData(Uri.parse("tel:" + phone));
        //开启系统拨号器
        activity.startActivity(intent);
    }

    /**
     * 视图初始化
     */
    protected abstract void initializeView();

    /**
     * 调用接口
     */
    protected abstract void loadDataFromServer();

    //电话弹框
    public void telDialog(final String tel) {
        final AlertDialog telDialog = new AlertDialog.Builder(this, R.style.dialogFullStyle).create();
        telDialog.show();
        telDialog.setCancelable(true);
        telDialog.setCanceledOnTouchOutside(false);
        Window window = telDialog.getWindow();
        window.setContentView(R.layout.tel_view);
        TextView tel_tv = (TextView) window.findViewById(R.id.tel_tv);
        tel_tv.setText(tel);
        TextView cancel_tv = (TextView) window.findViewById(R.id.cancel_tv);
        cancel_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                telDialog.dismiss();
            }
        });
        TextView submit_tv = (TextView) window.findViewById(R.id.submit_tv);
        submit_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                telDialog.dismiss();
                callPhone(tel);
            }
        });
    }

    /**
     * 显示dialog
     */
    protected void showPd() {
        try {
            if (null == pd) {
                pd = new CustomProgressDialog();
            }
            if (!pd.isAdded() && !pd.isVisible() && !pd.isRemoving()) {
                pd.show(getSupportFragmentManager(), "CustomProgressDialog");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void showPd(String msg) {
        try {
            if (null == pd) {
                pd = new CustomProgressDialog();
            }
            if (!pd.isAdded() && !pd.isVisible() && !pd.isRemoving()) {
                pd.show(getSupportFragmentManager(), "CustomProgressDialog");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 取消dialog
     */
    protected void hidePd() {
        try {
            if (null != pd) {
                pd.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转activity
     */
    public void openActivity(Class<?> pClass) {
        openActivity(pClass, null);
    }

    /**
     * 跳转activity
     */
    public void openActivity(Class<?> pClass, Bundle pBundle) {
        Intent intent = new Intent(context, pClass);
        if (pBundle != null) {
            intent.putExtras(pBundle);
        }
        context.startActivity(intent);
    }

    /**
     * 以下是权限相关
     */
    /**
     * 请求权限
     *
     * @param permissions 请求的权限
     * @param requestCode 请求权限的请求码
     */
    @TargetApi(Build.VERSION_CODES.M)
    public void requestPermission(String[] permissions, int requestCode) {
        this.REQUEST_CODE_PERMISSION = requestCode;
        if (checkPermissions(permissions)) {
            permissionSuccess(REQUEST_CODE_PERMISSION);
        } else {
            List<String> needPermissions = getDeniedPermissions(permissions);
            ActivityCompat.requestPermissions(activity, needPermissions.toArray(new String[needPermissions.size()]), REQUEST_CODE_PERMISSION);
        }
    }

    /**
     * 检测所有的权限是否都已授权
     */
    protected boolean checkPermissions(String[] permissions) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }

        for (String permission : permissions) {
            if (activity.checkSelfPermission(permission) !=
                    PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获取权限集中需要申请权限的列表
     */
    @TargetApi(Build.VERSION_CODES.M)
    private List<String> getDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (activity.checkSelfPermission(permission) !=
                    PackageManager.PERMISSION_GRANTED ||
                    activity.shouldShowRequestPermissionRationale(permission)) {
                needRequestPermissionList.add(permission);
            }
//            if (ContextCompat.checkSelfPermission(context, permission) !=
//                    PackageManager.PERMISSION_GRANTED ||
//                    ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
//                needRequestPermissionList.add(permission);
//            }
        }
        return needRequestPermissionList;
    }

    /**
     * 系统请求权限回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (verifyPermissions(grantResults)) {
                permissionSuccess(REQUEST_CODE_PERMISSION);
            } else {
                permissionFail(REQUEST_CODE_PERMISSION);
                showTipsDialog();
            }
        }
    }


    /**
     * 获取权限成功
     *
     * @param requestCode
     */
    public void permissionSuccess(int requestCode) {
        Log.d(TAG, "获取权限成功=" + requestCode);
        if (requestCode == permissionsLocationRequestCode) {// 开启定位权限
            Intent locationIntent = new Intent(context.getApplicationContext(), LocationService.class);
            startService(locationIntent);
        }
    }

    /**
     * 权限获取失败
     *
     * @param requestCode
     */
    public void permissionFail(int requestCode) {
        Log.d(TAG, "获取权限失败=" + requestCode);
    }

    /**
     * 确认所有的权限是否都已授权
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 显示提示对话框
     */
    private void showTipsDialog() {
        new AlertDialog.Builder(context)
                .setTitle("提示信息")
                .setMessage("当前应用缺少必要权限，该功能暂时无法使用。如若需要，请单击【确定】按钮前往设置中心进行权限授权。")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                }).show();
    }


    /**
     * 启动当前应用设置页面
     */
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    /**
     * 判断是否有加载更多,true还有加载更多，false加载完毕了
     */
    protected boolean ifNeedRefresh(int total, int page, int rows) {
        if (page * rows < total) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // 友盟的统计
//        MobclickAgent.onResume(this);

    }

    @Override
    public void onPause() {
        super.onPause();
        // 友盟的统计
//        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (pd != null) {
            try {
                pd.dismiss();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        unbinder.unbind();
        if (presenter != null) {
            presenter.close();
        }
    }

    AlertDialog.Builder gpsDialog;
    AlertDialog dialog;

    private void showOpenGpsDialog() {
        if (dialog != null && dialog.isShowing()) {// 之前弹出过了提示框
            return;
        }
        gpsDialog = new AlertDialog.Builder(activity);
        gpsDialog.setMessage("请前往开启gps");
        gpsDialog.setTitle("提示");
        gpsDialog.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            public void onClick(
                    DialogInterface paramAnonymousDialogInterface,
                    int paramAnonymousInt) {
                // 转到手机设置界面，用户设置GPS
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivityForResult(intent, 0); // 设置完成后返回到原来的界面
            }
        });
        // 屏蔽返回键，让客户必须点击
        gpsDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        gpsDialog.setCancelable(false);
        dialog = gpsDialog.create();
        dialog.show();
    }

    protected Uri fileUri;

    /**
     * 调用系统拍照的工具类
     */
    protected void camera(int requestCode) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        ContentValues values = new ContentValues();
        fileUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        startActivityForResult(intent, requestCode);
    }

    /**
     * 调用选取系统照片
     */
    protected void photo(int requestCode) {
        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, requestCode);
    }

    // 定位权限
    private static final String[] permissionsArray = new String[]{
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private int permissionsLocationRequestCode = 0x8888;// 定位权限的回调

    /**
     * 开启定位服务，先会访问定位权限
     */
    protected void startLocationService() {
        // 申请权限
        requestPermission(permissionsArray, permissionsLocationRequestCode);
    }

    AlertDialog.Builder localBuilder;

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }
}